package com.taotao.manage.controller;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EasyUIResult;
import com.taotao.manage.pojo.Item;
import com.taotao.manage.service.ItemService;

@Controller
@RequestMapping("item")
public class ItemController {

	@Autowired
	private ItemService itemService;

	/**
	 * 新增商品信息
	 * 
	 * @param item
	 * @param desc
	 * @return
	 */
	@PostMapping
	public ResponseEntity<Void> saveItem(Item item, @RequestParam("desc") String desc) {

		try {
			if (item == null || StringUtils.isEmpty(item.getTitle())) {
				return ResponseEntity.badRequest().build();
			}
			Boolean b = this.itemService.saveItemAndDesc(item, desc);
			if (b) {
				return ResponseEntity.status(HttpStatus.CREATED).build();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}

	/**
	 * 查询商品信息
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@GetMapping
	public ResponseEntity<EasyUIResult<Item>> queryItemListByPage(@RequestParam("page") Integer pageNum,
			@RequestParam("rows") Integer pageSize) {
		try {
			// 分页查询 并排序
			PageInfo<Item> pageInfo = this.itemService.queryByPageOrderBy("updated desc", pageNum, pageSize);
			// 判断结果集是否为null
			if (CollectionUtils.isEmpty(pageInfo.getList())) {
				// 如果为null，响应404
				return ResponseEntity.notFound().build();
			}
			// 响应200
			return ResponseEntity.ok(new EasyUIResult<>(pageInfo.getTotal(), pageInfo.getList()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 响应500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}

	/**
	 * 更新商品信息
	 * @param item
	 * @param desc
	 * @return
	 */
	@PutMapping
	public ResponseEntity<Void> updateItem(Item item, @RequestParam("desc") String desc) {
		try {
			// 执行更新操作
			Boolean b = this.itemService.updateItemAndDesc(item, desc);
			if (b) {
				// 更新成功
				return ResponseEntity.noContent().build();
			}
			// 更新不成功，响应400
			return ResponseEntity.badRequest().build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 响应500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	
}
